package com.sebscape.sebcms.security.services;

import javax.servlet.http.HttpServletRequest;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsStatics;

import com.sebscape.sebcms.Constants;
import com.sebscape.sebcms.pages.domain.Page;
import com.sebscape.sebcms.security.domain.User;

public class CmsPermissionsInterceptor extends AbstractInterceptor implements StrutsStatics {

	private static final long serialVersionUID = 863717614829991178L;
	private static Log log = LogFactory.getLog( CmsPermissionsInterceptor.class );
	
	public String intercept (ActionInvocation invocation) throws Exception {
		log.debug( "CmsPermissionsInterceptor invoked...");
	    // Get the action context from the invocation so we can access the
	    // HttpServletRequest and HttpSession objects.
	    final ActionContext context = invocation.getInvocationContext ();
	    HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
		try {
			// do the processing.
			processBefore( request );
			return invocation.invoke ();
		} catch (Exception e) {
			// THis means the user is NOT logged in.
			log.debug("CmsPermissionsIntercpetor: Exception raised: " + e.getMessage() );
			return "denied";
		}// end catch
	} // end method

	private void processBefore(HttpServletRequest request)
	throws Exception{
		// The page should have been loaded by the CmsPageLoaderInterceptor.
		Page page = (Page)request.getAttribute("sebCMS_page");
		if( page == null ){
			log.debug( "CmsPermissionsIntercpetor: NO CMS page in Request to process." );
			return;
		}
		// get the user from the session.
		User user = (User)request.getSession().getAttribute(Constants.ATTRIB_CURRENT_USER);
		// if the user is admin, they can view anything!
		if( user == null ){
			user = User.getAnonymousUser();
		} else  if( user.isMemberOf("System Administrators")){
			log.debug( "\"System Administrators\" can view anything.");
			return;
		} 
		//check page permissions if it is private.
		if( page.isViewableByUser( user ) ){
			return;
		} else {
			throw new Exception( "CmsPermissionsIntercpetor: User does not have permission to view this private page." );
		}
	}
	
}